<template>
  <div>
    <div class="input-group mt">
      <label>新闻标题：</label>
      <div class="input-group-box"><el-input v-model="title" placeholder="在此输入新闻标题（必须填写）"></el-input></div>
    </div>
    <div class="input-group mt">
      <label>新闻简介：</label>
      <div class="input-group-box"><el-input v-model="note" type="textarea" :rows="5" placeholder="输入新闻简介（100字以内）"></el-input></div>
    </div>
    <div class="input-group mt">
      <label>分类：</label>
      <div class="input-group-box">
        <el-select v-model="firstLevelCid" placeholder="一级分类" class="cycle-input"  @change="changeFirstLevel">
          <el-option key="" label="请选择一级分类" value=""></el-option>
          <el-option
            v-for="item in categoryList"
            :key="item.id"
            :label="item.name"
            :value="item.id">
          </el-option>
        </el-select>
        <el-select v-model="secondLevelCid" placeholder="二级分类" class="cycle-input"  @change="changeSecondLevel">
          <el-option key="" label="请选择二级分类" value=""></el-option>
          <el-option
            v-for="item in secondLevelCategoryList"
            :key="item.id"
            :label="item.name"
            :value="item.id">
          </el-option>
        </el-select>
      </div>
    </div>
    <div class="input-group">
      <label>作者：</label>
      <div class="input-group-box"><el-input v-model="author" placeholder="输入作者"></el-input></div>
    </div>
    <div class="input-group">
      <label>来源：</label>
      <div class="input-group-box"><el-input v-model="source" placeholder="输入来源"></el-input></div>
    </div>
    <div class="input-group"  v-if="isAdd">
      <label>设置类目推荐：</label>
      <div class="input-group-box">
        <el-switch
          v-model="isRecommend"
          on-text="是"
          off-text="否"
          on-value="1"
          off-value="0"> g
        </el-switch>
      </div>
    </div>
    <div class="input-group" v-if="isAdd">
      <label>设置为精选：</label>
      <div class="input-group-box">
        <el-switch
          v-model="isTop"
          on-text="是"
          off-text="否"
          on-value="1"
          off-value="0">
        </el-switch>
      </div>
    </div>
    <div class="input-group">
      <label>封面图片：</label>
      <div class="input-group-box cover-box">
        <img :src="cover.url" class="cover" v-if="cover.url!==''">
        <div class="el-upload el-upload--picture-card">
          <i class="el-icon-plus"></i>
          <input type="file" id="cover-img" accept="image/gif,image/jpeg,image/jpg,image/png,image/svg" class="zi_upload_input" @change="getfile($event)">
        </div>
        <span class="p-tip">* 建议尺寸190*140</span>
      </div>
    </div>

    <div class="input-group">
      <label>发布时间：</label>
      <div class="input-group-box">
        <el-date-picker
          v-model="repubTime"
          type="datetime"
          placeholder="请选择发布时间"
          format="yyyy-MM-dd HH:mm:ss"
          default-time="12:00:00">
        </el-date-picker>
      </div>
    </div>

    <div class="input-group">
      <label>归属于专题：</label>
      <div class="input-group-box">
        <el-select v-model="subjectId" filterable placeholder="请选择专题" class="cycle-input">
          <el-option key="0" label="不属于任何专题" value="0"></el-option>
          <el-option
            v-for="item in subjectList"
            :key="item.id"
            :label="item.name"
            :value="item.id">
          </el-option>
        </el-select>
      </div>
    </div>

    <div class="video" v-if="!showModifyVideo">
      <label>上传视频：</label>
      <div id="filePicker">选择文件</div>
      <div class="file-panel">
        <h2>文件上传区域</h2>
        <div class="file-list">
          <ul class="file-item" :class="`file-${file.id}`" v-for="file in fileList">
            <li class="file-type" :icon="fileCategory(file.ext)"></li>
            <li class="file-name">{{file.name}}</li>
            <li class="file-size">{{fileSize(file.size)}}</li>
            <li class="file-status">上传中...</li>
            <li class="file-operate">
           <!--   <a title="开始" @click="resume(file)"><i class="icon-sync"></i></a>
              <a title="暂停" @click="stop(file)"><i class="icon-authority"></i></a>-->
              <a title="移除" @click="remove(file)"><i class="icon-delete"></i></a>
            </li>
            <li class="progress"></li>
          </ul>
          <div class="no-file" v-if="!fileList.length"><i class="iconfont icon-empty-file"></i> 暂无待上传文件</div>
        </div>
      </div>
      <vue-upload
        :accept="accept"
        :url="url"
        :formData="videoFormData"
        :fileNumLimit="fileNumLimit"
        ref="uploader"
        uploadButton="#filePicker"
        :multiple="true"
        @beforeUpload="beforeUpload"
        @fileChange="fileChange"
        @progress="onProgress"
        @success="onSuccess"
      ></vue-upload>
    </div>
    <div class="video" style="margin-left: 40px;padding-top: 10px;" v-else>
      <el-button type="success" @click = 'showUploadFile'>重新上传视频</el-button>
    </div>

    <div class="bottom-box" v-if="isAdd">
      <el-button type="primary" size="small" @click="publish" :loading="publishLoading"> 立 即 发 布 </el-button>
      <el-button size="small" @click = 'saveAdd' :loading="saveAddLoading"> 保  存 </el-button>
    </div>
    <div class="bottom-box" v-else>
      <el-button size="small" @click = 'saveEditor' :loading="saveEditorLoading"> 保 存 修 改 </el-button>
    </div>
  </div>
</template>

<script>
  import apiConfig from '../../utils/apiconfig'
  import vueUpload from '../../components/upload'
  import api from '../../utils/api'
  import config from '../../utils/config'
  import WebUploader from '../../../static/lib/webuploader/webuploader.min.js'
  import $ from 'jquery'
  import helper from '../../utils/helper'
  export default {
    data () {
      return {
        title: '',
        author: '',
        source: '',
        newsDetail: '',
        note: '',
        cover: {
          url: '',
          img: ''
        },
        isPublished: true,
        isAdd: true,
        publishLoading: false,
        saveAddLoading: false,
        showModifyVideo: false,
        subjectId: 0,
        categoryList: [],
        subjectList: [],
        secondLevelCategoryList: [],
        firstLevelCid: '',
        secondLevelCid: '',
        cid: '',
        isTop: 0,
        isRecommend: 0,
        repubTime: '',
        // 文件上传的参数
        fileList: [],
        url: '',
        videoFormData: {
          md5: '',
          url: ''
        },
        fileNumLimit: 1, // 限制上传的个数
        accept: 'video',
        saveEditorLoading: false
      }
    },
    mounted () {

    },
    computed: {
      uploader () {
        return this.$refs.uploader
      }
    },
    created () {
      this.url = config.domain + helper.getManageApiUrl(apiConfig.fileUpload)

      this.getCategoryLevelOption()
      this.getSubjectList()
      var id = this.$route.query.id

      if (id && id !== '' && id !== 'undefined' && id !== null) {
        this.aid = id
        this.isAdd = false
        this.getNewsDetail()
      }
    },
    methods: {
      getfile (event) {
        this.cover.img = event.target.files[0]
        this.cover.url = window.URL.createObjectURL(this.cover.img)
      },
      getCategoryLevelOption () {
        var param = {
          is_video: 1
        }
        api.GET(helper.getManageApiUrl(apiConfig.newsCategoryAllLevel), param, res => {
          this.categoryList = res
        }, res => {
          console.log(res)
        })
      },
      getSubjectList () {
        var param = {
          param: ''
        }
        api.GET(helper.getManageApiUrl(apiConfig.getAllSubject), param, res => {
          this.subjectList = res
        }, res => {
          console.log(res)
        })
      },
      changeFirstLevel (val) {
        console.log(val)
        this.firstLevelCid = val
        this.categoryList.forEach((item) => {
          if (item.id === val) {
            this.secondLevelCategoryList = item.list
          }
        })
      },
      changeSecondLevel (val) {
        this.secondLevelCid = val
      },
      saveArt (status) {
        let formData = new FormData()
        formData.append('title', this.title)
        formData.append('content', this.newsDetail)
        formData.append('author', this.author)
        formData.append('source', this.source)
        formData.append('is_top', this.isTop)
        formData.append('is_recommend', this.isRecommend)
        formData.append('status', status)
        formData.append('note', this.note)
        formData.append('first_level_cid', this.firstLevelCid)
        formData.append('second_level_cid', this.secondLevelCid)
        formData.append('cover_path', this.cover.img)
        formData.append('video_url', this.videoFormData.url)
        formData.append('video_md5', this.videoFormData.md5)
        formData.append('repub_time', helper.formatDateTime(this.repubTime))
        formData.append('type', 1)
        formData.append('subject_id', this.subjectId)
        let configs = {
          headers: {
            'Content-Type': 'multipart/form-data'
          }
        }
        api.POST(helper.getManageApiUrl(apiConfig.addNews), formData, configs, res => {
//      api.GET(helper.getManageApiUrl(apiConfig.addNews), videoFormData, res => {
          var type = '保存'
          if (status === 1) {
            type = '发布'
          }
          this.$notify({
            title: '成功',
            message: type + '成功',
            type: 'success',
            duration: 1500
          })
          this.publishLoading = false
          this.saveAddLoading = false
          this.title = ''
          this.newsDetail = ''
          this.author = ''
          this.source = ''
          this.note = ''
          this.isTop = 0
          this.isRecommend = 0
          this.firstLevelCid = ''
          this.secondLevelCid = ''
          var cover = document.getElementById('cover-img')
          cover.value = ''
          this.cover.url = ''
          this.videoFormData.md5 = ''
          this.videoFormData.url = ''
          this.repubTime = ''
          this.subjectId = 0
          // 直接保存到英文
          api.POST(helper.getManageApiUrl(apiConfig.addNews), formData, configs, res => {
            console.log('save video to english edition success')
          }, res => {
            console.log('save video to english edition failed')
          }, true)
        }, res => {
          console.log(res)
        })
      },
      publish () {
//        var title = this.title.replace(/\s/g, '')
//        var author = this.author.replace(/\s/g, '')
//        var source = this.source.replace(/\s/g, '')
//        var note = this.note.replace(/\s/g, '')
        let note = this.note
        let title = this.title
        if (title.length === 0) {
          this.noEmpty('标题不能为空')
          return false
        }
        if (note.length === 0 || note.length > this.noteLimit) {
          this.noEmpty('新闻简介不能为空且必须' + this.noteLimit + '字以内')
          return false
        }
        if (this.firstLevelCid === '') {
          this.noEmpty('请选择一级分类')
          return false
        }
        if (this.secondLevelCid === '') {
          this.noEmpty('请选择二级分类')
          return false
        }
//        if (author.length === 0) {
//          this.noEmpty('新闻作者不能为空')
//          return false
//        }
//        if (source.length === 0) {
//          this.noEmpty('新闻来源不能为空')
//          return false
//        }
        if (this.cover.img === '') {
          this.noEmpty('封面图不能为空')
          return false
        }

        if (this.videoFormData.md5 === '') {
          this.noEmpty('请上传文件')
          return false
        }
        this.publishLoading = true
        this.saveArt(1)
      },
      saveAdd () {
//        var title = this.title.replace(/\s/g, '')
//        var author = this.author.replace(/\s/g, '')
//        var source = this.source.replace(/\s/g, '')
//        var note = this.note.replace(/\s/g, '')
        let note = this.note
        let title = this.title
        if (title.length === 0) {
          this.noEmpty('标题不能为空')
          return false
        }
//        if (this.newsDetail === '') {
//          this.noEmpty('新闻内容不能为空')
//          return false
//        }
        if (note.length === 0 || note.length > this.noteLimit) {
          this.noEmpty('新闻简介不能为空且必须' + this.noteLimit + '字以内')
          return false
        }
        if (this.firstLevelCid === '') {
          this.noEmpty('请选择一级分类')
          return false
        }
        if (this.secondLevelCid === '') {
          this.noEmpty('请选择二级分类')
          return false
        }
//        if (author.length === 0) {
//          this.noEmpty('新闻作者不能为空')
//          return false
//        }
//        if (source.length === 0) {
//          this.noEmpty('新闻来源不能为空')
//          return false
//        }
        if (this.cover.img === '') {
          this.noEmpty('封面图不能为空')
          return false
        }

        if (this.videoFormData.md5 === '') {
          this.noEmpty('请上传文件')
          return false
        }
        this.saveAddLoading = true
        this.saveArt(0)
      },
      saveEditor () {
//        var title = this.title.replace(/\s/g, '')
//        var note = this.note.replace(/\s/g, '')
        var author = this.author.replace(/\s/g, '')
        var source = this.source.replace(/\s/g, '')
        let note = this.note
        let title = this.title
        if (title.length === 0) {
          this.noEmpty('标题不能为空')
          return false
        }
//        if (this.newsDetail === '') {
//          this.noEmpty('新闻内容不能为空')
//          return false
//        }
        if (note.length === 0 || note.length > this.noteLimit) {
          this.noEmpty('新闻简介不能为空且必须' + this.noteLimit + '字以内')
          return false
        }
        if (this.firstLevelCid === '') {
          this.noEmpty('请选择一级分类')
          return false
        }
        if (this.secondLevelCid === '') {
          this.noEmpty('请选择二级分类')
          return false
        }
//        if (author.length === 0) {
//          this.noEmpty('新闻作者不能为空')
//          return false
//        }
//        if (source.length === 0) {
//          this.noEmpty('新闻来源不能为空')
//          return false
//        }
        if (this.cover.img === '') {
          this.noEmpty('封面图不能为空')
          return false
        }

        if (this.videoFormData.md5 === '') {
          this.noEmpty('请上传文件')
          return false
        }
        this.saveEditorLoading = true
        let formData = new FormData()
        formData.append('id', this.aid)
        formData.append('title', this.title)
        formData.append('content', this.newsDetail)
        formData.append('is_recommend', this.isRecommend)
        formData.append('author', author)
        formData.append('source', source)
        formData.append('note', note)
        formData.append('first_level_cid', this.firstLevelCid)
        formData.append('second_level_cid', this.secondLevelCid)
        formData.append('cover_path', this.cover.img)
        formData.append('video_url', this.videoFormData.url)
        formData.append('video_md5', this.videoFormData.md5)
        formData.append('repub_time', helper.formatDateTime(this.repubTime))
        formData.append('type', 1)
        formData.append('subject_id', this.subjectId)
        let configs = {
          headers: {
            'Content-Type': 'multipart/form-data'
          }
        }
        api.POST(helper.getManageApiUrl(apiConfig.updateNews), formData, configs, res => {
          this.$notify({
            title: '成功',
            message: '修改已保存',
            type: 'success',
            duration: 1500
          })
          this.saveEditorLoading = false
          // this.$router.push('/index/news/list/51')
          window.history.go(-1)
        }, res => {
          this.noEmpty(res.msg)
        })
      },
      showUploadFile () {
        this.showModifyVideo = !this.showModifyVideo
      },
      getNewsDetail () { // 修改新闻时，首先获取新闻内容
        this.loadPreview = true
        var param = {
          id: this.aid
        }
        api.GET(helper.getManageApiUrl(apiConfig.newsDetail), param, res => {
          var resData = res
          this.firstLevelCid = resData.first_level_cid
          this.secondLevelCid = resData.second_level_cid
          this.title = resData.title
          this.author = resData.author
          this.source = resData.source
          this.isTop = resData.is_top
          this.isRecommend = resData.is_recommend
          this.note = resData.note
          this.newsDetail = resData.content
          this.cover.url = resData.cover_path
          this.cover.img = resData.cover_path
          this.videoFormData.md5 = resData.video_md5
          this.videoFormData.url = resData.video_url
          this.repubTime = resData.repub_time
          this.subjectId = resData.subject_id
          // 初始话二级分类
          let _this = this
          this.categoryList.forEach((item) => {
            if (item.id === this.firstLevelCid) {
              _this.secondLevelCategoryList = item.list
            }
          })
          this.loadPreview = false
          this.showModifyVideo = true
        }, res => {
          this.noEmpty('获取数据失败')
        })
      },
      noEmpty (tip) {
        this.$notify({
          title: '提示',
          message: tip,
          type: 'error',
          duration: 1500
        })
      },
      fileChange (file) {
        console.log('正在计算MD5值...')
        if (!file.size) {
          return
        }
        this.fileList.push(file)
      },
      // 开始上传之前的事件，可以用于断点续传
      beforeUpload (block, data) {
      },

      onProgress (file, percent) {
        $(`.file-${file.id} .progress`).css('width', percent * 100 + '%')
        $(`.file-${file.id} .file-status`).html((percent * 100).toFixed(2) + '%')
      },
      onSuccess (file, response) {
        console.log('上传成功', response)
        let $fileStatus = $(`.file-${file.id} .file-status`)
        $fileStatus.html('上传成功，转码中')
        if (response.errcode === 200) {
          let md5 = response.data.md5
          let fileType = response.data.type
          let param = {
            'md5': md5,
            'file_name': file.name,
            'file_type': fileType
          }
          this.videoFormData.md5 = md5
          this.videoFormData.url = md5 + '.' + fileType
          api.GET(helper.getManageApiUrl(apiConfig.fileMerge), param, res => {
            console.log('上传结果', res)
            if (res.status === 200) {
              $fileStatus.html('上传成功，转码中')
            } else if (res.status === 1) {
              $fileStatus.html('上传失败')
            } else if (res.status === 2) {
              $fileStatus.html('上传成功')
            }
          }, res => {
            console.log(res)
          })
        }
      },

      uploadError (file, reason) {
        this.uploader.retry(file)
      },

      resume (file) {
        this.uploader.upload(file)
      },
      stop (file) {
        this.uploader.stop(file)
      },
      remove (file) {
        // 取消并中断文件上传
        this.uploader.cancelFile(file)
        // 在队列中移除文件
        this.uploader.removeFile(file, true)

        // 在ui上移除
        let index = this.fileList.findIndex(ele => ele.id === file.id)
        this.fileList.splice(index, 1)
      },

      fileSize (size) {
        return WebUploader.Base.formatSize(size)
      },
      fileCategory (ext) {
        let type = ''

        const typeMap = {
          image: ['gif', 'jpg', 'jpeg', 'png', 'bmp', 'webp'],
          video: ['mp4', 'm3u8', 'rmvb', 'avi', 'swf', '3gp', 'mkv', 'flv'],
          text: ['doc', 'txt', 'docx', 'pages', 'epub', 'pdf', 'numbers', 'csv', 'xls', 'xlsx', 'keynote', 'ppt', 'pptx']
        }

        Object.keys(typeMap).forEach((_type) => {
          const extensions = typeMap[_type]
          if (extensions.indexOf(ext) > -1) {
            type = _type
          }
        })
        return type
      }
    },
    watch: {},
    components: {
      vueUpload
    }
  }
</script>

<style>
  .art-fade {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    z-index: 99;
    background: rgba(255, 255, 255, 0.7);
    padding-top: 5%;
  }
  .input-group-box .el-upload--picture-card {
    position: relative;
    width: 100px;
    height: 100px;
  }
  .input-group-box img.cover {
    width: 95px;
    height: 71px;
    display: block;
    margin-bottom: 10px;
  }
  .input-group-box .el-upload--picture-card i {
    position: absolute;
    top: 35px;
    left: 35px;
  }
  .el-upload--picture-card .zi_upload_input {
    position: absolute;
    display: inline-block;
    width: 100%;
    height: 100%;
    opacity: 0;
    top: 0;
    left: 0;
    cursor: pointer;
  }
  .input-group .input-group-box label.el-switch {
    width: auto;
    line-height: auto;
    margin-top: 7px;
    vertical-align: top
  }
  .art-title-box {
    margin-bottom: 8px;
    padding: 0px 25px;
  }
  .art-title{
    width: 100%;
    border: none;
    background-color: transparent;
    color: #000;
    font-size: 22px;
    height: 45px;
    line-height: 45px;
  }
  .input-group.mt {
    margin-top: 24px;
  }
  .bottom-box {
    position: fixed;
    bottom: 0;
    box-sizing: border-box;
    width: 100%;
    left: 180px;
    background: #f2f2f2;
    border-top: 1px solid #dedede;
    height: 50px;
    text-align: right;
    line-height: 50px;
    padding-right: 350px;
  }
  .bottom-box .el-button {
    margin-left: 25px;
  }
  .cover-box .p-tip {
    display: inline-block;
    color: red;
    font-size: 12px;
    margin-top: 80px;
    margin-left: 10px;
  }

  .video label{
    display: inline-block;
    flex: 0 0 100px;
    width: 100px;
    text-align: right;
    font-size: 14px;
    color: #999;
    line-height: 36px;
    padding-right: 15px;
  }
  #filePicker {
    margin-left: 100px;
  }
  .file-panel {
    width: 90%;
    margin-top: 10px;
    margin-left: 100px;
    margin-bottom: 20px;
    height: 300px;
    box-shadow: 0 2px 12px 1px rgba(0, 0, 0, 0.1);
  }
  .file-panel h2 {
      height: 40px;
      line-height: 40px;
      padding: 0 10px;
      border-radius: 4px 4px 0 0;
      border-bottom: 1px solid #ccc;
      background-color: #fff;
    }

  .file-panel .file-list {
      position: relative;
      height: 260px;
      overflow-y: auto;
      background-color: rgb(250, 250, 250);
    }

  .file-panel  .file-item {
    position: relative;
    height: 50px;
    line-height: 50px;
    padding: 0 10px;
    border-bottom: 1px solid #ccc;
    background-color: #fff;
    z-index: 1
  }

  .file-panel  .file-item li {
        display: inline-block;
  }
  .file-panel  .file-type {
      width: 24px;
      height: 24px;
      vertical-align: -5px;
    }
  .file-panel  .file-name {
      width: 40%;
      margin-left: 10px;
  }
  .file-panel  .file-size {
      width: 20%;
  }
  .file-panel .file-status {
      width: 20%;
  }
  .file-panel .file-operate {
    width: 10%;
  }
  .file-panel .file-operate a {
    padding: 10px 5px;
    cursor: pointer;
    color: #666;
  }
  .file-panel .file-operate a:hover {
    color: #ff4081;
  }
  .file-panel  .file-type[icon=text] {
      background: url(../../../src/img/icon/icon-text.png);
  }
  .file-panel .file-type[icon=video] {
      background: url(../../../src/img/icon/icon-video.png);
  }
  .file-panel .file-type[icon=image] {
      background: url(../../../src/img/icon/icon-img.png);
  }

  .file-panel .progress {
      position: absolute;
      top: 0;
      left: 0;
      height: 49px;
      width: 0;
      background-color: #E2EDFE;
      z-index: -1;
    }

  .file-panel .no-file {
      position: absolute;
      top: 50%;
      left: 50%;
      transform: translate(-50%, -50%);
      font-size: 16px;
  }
</style>
